package cn.mw.cmdb.config;

import cn.mw.microMonitorCommon.util.ModuleIDManager;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import org.javers.core.Javers;
import org.javers.core.JaversBuilder;
import org.javers.repository.mongo.MongoRepository;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@Configuration
public class CMDBConfiguration {
    @Bean
    public MongodbAutoIdEventListener mongodbAutoIdEvent(ModuleIDManager moduleIDManager){
        return new MongodbAutoIdEventListener(moduleIDManager);
    }

    @Bean
    public LocalValidatorFactoryBean validator(MessageSource messageSource) {
        LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
        validatorFactoryBean.setValidationMessageSource(messageSource);
        return validatorFactoryBean;
    }

    @Bean
    public Javers javers(MongoProperties mongoProperties) {
        String mongoScheme = "mongodb://";
        String uri = mongoProperties.getUri().replace(mongoScheme ,"");
        StringBuilder sb = new StringBuilder(mongoScheme).append(mongoProperties.getUsername())
                .append(":").append(mongoProperties.getPassword()).append("@").append(uri)
                .append("?authSource=").append(mongoProperties.getAuthenticationDatabase());
        String connUri = sb.toString();
        int dbNameIndexStart = connUri.lastIndexOf("/") + 1;
        int dbNameIndexEnd = connUri.lastIndexOf("?");
        String dbName = connUri.substring(dbNameIndexStart ,dbNameIndexEnd);
        MongoDatabase mongoDb = MongoClients.create(connUri).getDatabase(dbName);
        MongoRepository mongoRepository = new MongoRepository(mongoDb);
        Javers javers = JaversBuilder.javers().registerJaversRepository(mongoRepository).build();
        return javers;
    }

}
